package com.kaluli.project.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kaluli.project.domain.entity.KllOrderSynApi;
import com.kaluli.project.domain.entity.KllZZMessage;
import com.kaluli.project.domain.entity.Response;
import com.kaluli.project.domain.entity.ResultType;
import com.kaluli.project.service.KllDataService;
import com.kaluli.project.service.KllMainOrderService;
import com.kaluli.project.service.KllOrderSynApiService;
import com.kaluli.project.service.KllZZMessageService;
import com.kaluli.project.service.KllZZOpService;
import com.kaluli.project.service.RestClient;
import com.kaluli.project.service.SendEmailService;
import com.kaluli.project.service.TradePool;
import com.kaluli.project.service.TradeQueue;
import com.kaluli.project.utils.RandomNumber;

/**
 * 卓志Op平台 试用的外调接口
 * 
 * @author zyzowen1944
 * 
 */
@Controller
@Transactional
@PropertySource({ "classpath:thridsystem.properties" })
public class ZZOpController {
	
	
	private static Logger log = Logger.getLogger(ZZOpController.class);
	
	private static final String FLAG = "KLL";
	
	@Autowired
	private Environment env;
	
	@Autowired
	private SendEmailService sendEmailService;
	
	@Autowired
	private KllZZMessageService kllZZMessageService;
	
	@Autowired
	private KllMainOrderService kllMainOrderService;
	
	@Autowired
	private KllOrderSynApiService kllOrderSynApiService;
	
	@Autowired
	private KllDataService dataService;
	
	@Autowired
	private KllZZOpService zzopService;
	
	@Autowired
	private RestClient client;
	
	@RequestMapping(value = "/zz/logisticAPI", method = RequestMethod.POST)
	public ModelAndView receiveZZlogistics(String enOrderCode,String wayBillNo,@RequestBody byte[] bytes, HttpServletRequest request) throws IOException {
		Map<String, Object> map1 = new HashMap<String, Object>();
		String reqBody = new String(bytes, "utf-8");
	    JSONObject	ja =JSON.parseObject(reqBody);
	    String orderNum = ja.getString("enOrderCode");
	    String expressNumber = ja.getString("wayBillNo");
	    log.info("logisticAPI_json="+reqBody);
	    log.info("orderNumber="+orderNum);
	    
		if(StringUtils.isNotBlank(orderNum)){
			try {
				//验证orderNum是否属于本平台
				if(orderNum.contains(FLAG)){
					TradePool pool = TradePool.getTradeInstance();
					TradeQueue queue = pool.getTradeQueue("ZZ-out");
					KllOrderSynApi osa = new KllOrderSynApi();
					osa.setOrderNumber(orderNum);//接受的是ibilling
					String id = new Date().getTime()+RandomNumber.getRandom();
					osa.setId(Long.valueOf(id));
					osa.setIbillingNumber(orderNum);
					osa.setLogisticJSON(reqBody);
					
					queue.add(osa);
					
					
					//物流
					kllMainOrderService.updateLogistics(orderNum, expressNumber);
				
					map1.put("status", 1);
					map1.put("notes", "成功");
				}else{
					//调用易宝推单平台
					StringBuffer url = new StringBuffer();
					url.append(env.getProperty("bb.url"));
					url.append("enOrderCode="+orderNum);
					url.append("&wayBillNo="+expressNumber);
					String response =client.post(url.toString());
					map1.put("status", 1);
					map1.put("notes", response);
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				map1.put("status", -1);
				map1.put("notes", "系统异常");
			}
		}else{
			map1.put("status", -1);
			map1.put("notes", "参数不正确!");
		}

		return new ModelAndView(new MappingJacksonJsonView(), map1);
	}
	
	
	@RequestMapping(value = "/zz/message", method = RequestMethod.POST)
	public ModelAndView receiveZZMessage(@RequestBody byte[] bytes, HttpServletRequest request) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		String reqBody = new String(bytes, "utf-8");
	    JSONObject	ja =JSON.parseObject(reqBody);
	    String reportId = ja.getString("reportId");
	    String orderNo = ja.getString("orderNo");
	    String applyTime = ja.getString("applyTime");
	    String status = ja.getString("status");
	    String wayBillNo = ja.getString("wayBillNo");
	    String logisticsName = ja.getString("logisticsName");
	    String logisticsCode = ja.getString("logisticsCode");
	    String notes = ja.getString("notes");
	    log.info("zz_message:orderNo="+orderNo+"&notes="+notes);
	    //清关失败状态处理
	    for(ResultType type:ResultType.values()){
	    	if(type.getValue().equals(status)){
	    		//更新推送卓志状态为5
	    		kllOrderSynApiService.updateZZStatus(orderNo);
	    		//发邮件通知
	    		StringBuffer content = new StringBuffer();
	    		content.append("一.清关异常订单\r\n");
	    		content.append("ibilling号:"+orderNo+"\r\n");
	    		content.append("=>=>=>错误信息===:" + reqBody + "\r\n");
	    		String emails = env.getProperty("nsapi.mail.receiver");
				try {
					sendEmailService.sendExmail(content.toString(), emails);
				} catch (MessagingException e) {
					e.printStackTrace();
				}
	    	}
	    }
	    
	   
		if(StringUtils.isNotBlank(orderNo)){
			try {
				KllZZMessage mes = new KllZZMessage();
			    mes.setReportId(reportId);
			    mes.setOrderNo(orderNo);
			    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			    mes.setApplyTime(sf.parse(applyTime));
			    mes.setStatus(status);
			    mes.setWayBillNo(wayBillNo);
			    mes.setLogisticsCode(logisticsCode);
			    mes.setLogisticsName(logisticsName);
			    mes.setNotes(notes);
			    mes.setCreate_time(new Date());
			    mes.setUpdate_time(new Date());
			    kllMainOrderService.saveMessage(mes);
			    map.put("orderId", orderNo);
				map.put("status", 1);
				map.put("notes", "成功");
			} catch (Exception e) {
				e.printStackTrace();
				map.put("orderId", orderNo);
				map.put("status", -1);
				map.put("notes", "系统异常");
			}
		}else{
			map.put("orderId", orderNo);
			map.put("status", -1);
			map.put("notes", "参数不正确!");
		}

		return new ModelAndView(new MappingJacksonJsonView(), map);
	}
	
	
	
	@RequestMapping(value = "/test/stock", method = RequestMethod.POST)
	@ResponseBody
	public ModelAndView testStock(@RequestBody byte[] bytes) throws UnsupportedEncodingException {
		Map<String, Object> map = new HashMap<>();
		String result = "";
		try {
			result = zzopService.getZZOpStock();
		} catch (IOException e) {
			e.printStackTrace();
		}
		map.put("data", result);
		return new ModelAndView(new MappingJacksonJsonView(), map);
	}
	
	@RequestMapping(value = "/test/api", method = RequestMethod.POST)
	@ResponseBody
	public ModelAndView testApi(@RequestBody byte[] bytes) throws UnsupportedEncodingException {
		Map<String, Object> map = new HashMap<>();
		kllOrderSynApiService.sendExmail();
		return new ModelAndView(new MappingJacksonJsonView(), map);
	}
	
	
	
	
	
	@RequestMapping(value = "/edb/update", method = RequestMethod.POST)
	@ResponseBody
	public ModelAndView updateEDB(@RequestBody byte[] bytes) throws UnsupportedEncodingException {
		Map<String, Object> map = new HashMap<>();
		String reqBody = new String(bytes, "utf-8");
	    JSONObject	ja =JSON.parseObject(reqBody);
	    String ibillingNumber = ja.getString("ibillingNumber");
	    try {
			if(StringUtils.isNotBlank(ibillingNumber)){
				
//				kllMainOrderService.updateEDBstock(ibillingNumber);
				map.put("status", 1);
				map.put("notes", "成功");
			}
		} catch (Exception e) {
			map.put("status", -1);
			map.put("notes", "失败");
		}
		return new ModelAndView(new MappingJacksonJsonView(), map);
	}
	
	
}
